package com.cxc.java8;

import java.util.Arrays;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.stream.Stream;

public class StreamFind {
    public static void main(String[] args) {

        Stream<Integer> stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});
        Optional<Integer> result = stream.filter(i -> i % 2 == 0).findAny();
        System.out.println(result.get());

        stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});
        Optional<Integer> result1 = stream.filter(i->i<10).findAny();
        System.out.println(result1.get());
        System.out.println(result1.orElse(-1));

        System.out.println( "---------findFirst-------");
        stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});
        Optional<Integer> result2 = stream.filter(i -> i % 2 == 0).findFirst();
        result2.ifPresent(System.out::println);

        System.out.println(result2.filter(i -> i == 2).get());

        int result3 = findOBJ(new Integer[]{1, 2, 3, 4, 5, 6, 7}, -1, i -> i < 10);
        System.out.println(result3);

    }

    private static int findOBJ(Integer[] values, int defaultValue, Predicate<Integer> predicate){

        for (int i:values){
            if(predicate.test(i)){
                return i;
            }
        }
        return defaultValue;
    }


}
